<?php

class DispatchTechController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';
    public $location;
    public $dispatch;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($dispatch) {
        $model = new DispatchTech;
        $model->dispatch = $dispatch;


        if (isset($_POST['DispatchTech'])) {

            $model->attributes = $_POST['DispatchTech'];
            if ($model->save()) {
                echo 'Save successful';
            } else {
                echo json_encode($model->getErrors());
            }
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate() {
        $model = $this->loadModel($_POST['id']);
        /* @var $model DispatchTech */
        $oldStatus = $model->status;
        $lastEmpno = $model->empno;
        $empno = Yii::app()->request->getPost('empno');
        if (DispatchUtil::canEditTech($model) && isset($_POST['DispatchTech'])) {


            $model->changeStatus($_POST['DispatchTech']['status'],$empno);
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $model = $this->loadModel($id);

        $model->delete();
    }

    public function actionSaveTech() {
        if (isset($_POST['dispatch'])) {


            //update the first
            $unassign = DispatchTech::model()->find('empno=:empno AND dispatch=:dispatch', array(
                'empno' => '0000',
                'dispatch'=>$_POST['dispatch']
                    ));
            if ($unassign != NULL) {
                $unassign->enddate = date('Y-m-d');
                $unassign->endtime = date('H:i:s');
                $unassign->save();
            }



            $tech = new DispatchTech;
            if (isset($_POST['data'])) {
                $tech->empno = $_POST['data']['empno'];
            } else if (isset($_POST['unassign'])) {
                $tech->empno = '0000';
            } else{
                return false;
            }
            $tech->dispatch = $_POST['dispatch'];
            $tech->status = 'Pending';
            $tech->startdate = date('Y-m-d');
            $tech->starttime = date('H:i:s');

            if ($tech->save()) {
                echo "Successful";
            } else {
                echo json_encode($tech->errors);
            }
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex($dispatch) {
        $this->loadObject($dispatch);
        $this->render('index', array(
            'dispatch' => $this->dispatch,
            'location' => $this->location
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = DispatchTech::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function loadObject($dispatch) {
        $this->dispatch = Dispatchdetails::model()->findByPk($dispatch);
        if ($this->dispatch == NULL)
            throw new CHttpException(404, 'The requested page does not exist.');
        $this->location = Locations::model()->find('custno=:custno AND locno=:locno', array(
            'custno' => $this->dispatch->custno,
            'locno' => $this->dispatch->locno
                ));
        if ($this->location == NULL)
            throw new CHttpException(404, 'The requested page does not exist.');
    }

    public function actionList($dispatch, $page=0, $sort=NULL) {
        if ($page > 0)
            $page--;
        $order = CJSON::decode($sort);
        $crit = new CDbCriteria();
        $crit->condition = 'dispatch=:dispatch';
        $crit->params = array(
            'dispatch' => $dispatch
        );
        if ($sort != NULL) {
            $crit->order = $order[0]['property'] . ' ' . $order[0]['direction'];
        } else {
            $crit->order = 'dispatch, counter';
        }
        $data = new CActiveDataProvider('DispatchTech', array(
                    'criteria' => $crit,
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page
                    )
                ));

        if ($data != NULL && count($data->getData()) > 0) {
            $rs = array();
            $rs['totalCount'] = $data->getTotalItemCount();
            foreach ($data->getData() as $i => $item) {
                $rs['data'][$i] = $item->getAttributes();
                if ($rs['data'][$i]['empno'] == NULL)
                    $rs['data'][$i]['empnoText'] = '0000 - Unassigned';
                else if ($item->employee != NULL)
                    $rs['data'][$i]['empnoText'] = $item->employee->firstname . ' ' . $item->employee->lastname;
                $rs['data'][$i]['starttime'] = convertDate('h:i A', $item->starttime);
                $rs['data'][$i]['endtime'] = convertDate('h:i A', $item->endtime);
                if ($item->endtime == '00:00:00')
                    $rs['data'][$i]['endtime'] = NULL;
                if ($item->enddate == '0000-00-00')
                    $rs['data'][$i]['enddate'] = NULL;
            }
            echo json_encode($rs);
        }
    }

}
